<script setup>
import { ref, onMounted } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { fileUpload } from '@/api/server/file'
const content = defineModel()
const editor = ref(null)
const vditorRef = ref(null)

onMounted(() => {
  editor.value = new Vditor(vditorRef.value, {
    minHeight: 470,
    height: 720,
    theme: 'dark',
    toolbarConfig: {
      pin: true
    },
    cache: {
      enable: false
    },
    tab: '    ',
    placeholder: '笔记空空',
    mode: 'ir',
    preview: {
      mode: 'both',
      comment: {
        enable: true
      },
      theme: {
        current: 'dark',
        list: {
          'ant-design': 'Ant Design',
          dark: 'Dark',
          light: 'Light',
          wechat: 'WeChat'
        }
      }
    },
    image: {
      isPreview: true
    },
    upload: {
      url: '/file/upload',
      max: 10 * 1024 * 1024,
      accept: 'image/jpeg,image/png,image/gif,image/jpg,image/bmp', // 图片格式
      multiple: true, // 是否允许批量上传
      // fieldName: 'files', // 上传字段名称
      async handler(files) {
        const formData = new FormData()
        for (const index in files) {
          formData.append('files', files[index])
        }
        const res = await fileUpload(formData)
        res.data.forEach((file) => {
          editor.value.insertValue(`![图片](${file})`)
        })
      }
    },
    input(md) {
      content.value = md
    },
    after: () => {
      if (content.value === null) return
      editor.value.setValue(content.value)
    }
  })
})
</script>
<template>
  <div class="editor">
    <div id="vditor" ref="vditorRef"><el-skeleton :rows="10" animated /></div>
  </div>
</template>

<style scoped lang="scss">
.editor {
  max-height: 600px;
  #vdioter {
    max-height: 100%;
  }
}
</style>
